<template>
  <div class="account-box">
    <!-- 账号登录和短信验证码登录切换 -->
    <div class="toggle">
      <a @click="isAccountLogin = true" href="javascript:;" v-if="!isAccountLogin">
        <i class="iconfont icon-user"></i> 使用账号登录
      </a>
      <a @click="isAccountLogin = false" href="javascript:;" v-else>
        <i class="iconfont icon-msg"></i> 使用短信登录
      </a>
    </div>
    <!-- 登录表单 -->
    <!--schema是定义的验证规则; v-slot是作用域插槽，把验证组件中的错误信息传递到errors对象 -->
    <Form ref="loginForm" class="form" :validation-schema="schema" v-slot="{ errors }" autocomplete="off">
      <template v-if="isAccountLogin">
        <!-- 账号登录的表单 -->
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <Field :class="{ error: errors.account }" type="text" v-model="form.account" name="account"
              placeholder="请输入用户名或手机号" />
          </div>
          <!-- 如果验证失败，错误显示在此处,验证通过不显示-->
          <div class="error" v-if="errors.account"><i class="iconfont icon-warning" /> {{ errors.account }}</div>
        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-lock"></i>
            <Field :class="{ error: errors.password }" type="password" v-model="form.password" name="password"
              placeholder="请输入密码" />
          </div>
          <!-- 有错误就显示 -->
          <div class="error" v-if="errors.password"><i class="iconfont icon-warning" /> {{ errors.password }}</div>
        </div>
      </template>
      <template v-else>
        <!-- 短信验证码登录 -->
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <Field :class="{ error: errors.mobile }" type="text" v-model="form.mobile" name="mobile"
              placeholder="请输入手机号" />
          </div>
          <div class="error" v-if="errors.mobile"><i class="iconfont icon-warning" /> {{ errors.mobile }}</div>
        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-code"></i>
            <Field :class="{ error: errors.code }" type="text" v-model="form.code" name="code" placeholder="请输入验证码" />
            <button ref="codeCom" @click.prevent="send" class="code">
              {{ time === 0 ? '发送验证码' : `${time}s后发送` }}
            </button>
          </div>
          <div class="error" v-if="errors.code"><i class="iconfont icon-warning" /> {{ errors.code }}</div>
        </div>
      </template>
      <div class="form-item">
        <div class="agree">
          <!-- 复选框组件:当将组件名称变成Field后，就变成了文本输入框，如果希望保持原来组件的特性，使用as属性指向组件名称即可 -->
          <Field as="xtx-checkbox" name="isAgree" v-model="form.isAgree" />
          <!--    <xtx-checkbox v-model="form.isAgree"></xtx-checkbox> -->
          <span>我已同意</span>
          <a href="javascript:;">《隐私条款》</a>
          <span>和</span>
          <a href="javascript:;">《服务条款》</a>
        </div>
        <div class="error" v-if="errors.isAgree"><i class="iconfont icon-warning" /> {{ errors.isAgree }}</div>
      </div>
      <a @click="login" href="javascript:;" class="btn">登录</a>
    </Form>
    <div class="action">
      <img src="https://qzonestyle.gtimg.cn/qzone/vas/opensns/res/img/Connect_logo_7.png" alt="">
      <div class="url">
        <a href="javascript:;">忘记密码</a>
        <a href="javascript:;">免费注册</a>
      </div>
    </div>
  </div>
</template>
<script setup>
import { Form, Field } from 'vee-validate'
import { getCurrentInstance, reactive, ref, watch } from 'vue'
// 从配置选项中导入公用的验证规则
import { myFormValidate } from '@/config'
import { userAccountLogin, userMobileLoginMsg } from '@/api/login'
import { useStore } from 'vuex'
import { useRoute, useRouter } from 'vue-router'
// import Message from '@/components/library/message'
// 获取组件实例
const { proxy: app } = getCurrentInstance()
const store = useStore()
const router = useRouter()
const route = useRoute()
// console.log(router.currentRoute.value)
// 定义本表单的验证规则
const schema = {
  account: myFormValidate.account,
  password: myFormValidate.password,
  mobile: myFormValidate.mobile,
  code: myFormValidate.code,
  isAgree: myFormValidate.isAgree
}
// 定义表单数据
const form = reactive({
  isAgree: true,
  account: 'lau0400810121',
  password: '123456',
  mobile: 18665455185,
  code: null
})
// 默认的表单登录方式为账号登录
const isAccountLogin = ref(false)
// 表单对象
const loginForm = ref(null)
// 切换不同的表单登录方式时：1.清空原来表单输入内容;2.验证失败的信息清空
watch(isAccountLogin, () => {
  // 清空原来表单输入内容
  Object.keys(form).forEach(key => {
    form[key] = null
  })
  form.isAgree = true
  // 验证失败的信息清空
  loginForm.value.resetForm()
})
// 登录时发送短信验证码
const codeCom = ref(null)
const time = ref(0)
let timer = null
function send() {
  // 需要对用户填写的手机号码做校验
  //  由于点击发送验证码的行为，并不需要手机号码选项失去焦点或者是提交表单时触发，主动触发表单的验证规则
  const mobileValid = schema.mobile(form.mobile)
  if (mobileValid === true) {
    // 代表是标准的手机号码,可以发送短信
    userMobileLoginMsg(form.mobile).then(() => {
      time.value = 60
      // 按钮禁用
      codeCom.value.disabled = true
      // 开启定时器
      timer = setInterval(() => {
        if (time.value <= 0) {
          // 清除定时器
          clearInterval(timer)
          // 按钮可用
          codeCom.value.disabled = false
          time.value = 0
        } else {
          time.value--
        }
      }, 1000)
    }).catch(e => {
      app.$message({ type: 'error', text: e.response.data.message || '短信发送失败' })
    })
  } else {
    // 失败，使用vee的错误函数显示错误信息 setFieldError(字段,错误信息)
    loginForm.value.setFieldError('mobile', mobileValid)
  }
}

// 登录
// 需要在点击登录的时候对整体表单进行校验
async function login() {
  // Form组件提供了一个 validate 函数作为整体表单校验，当是返回的是一个promise
  const valid = await loginForm.value.validate()
  if (valid) {
    if (isAccountLogin.value) {
      // 账号登录
      try {
        // 账号登录
        const { result } = await userAccountLogin({ account: form.account, password: form.password })
        console.log(result)
        const { id, account, mobile, avatar, token, nickname } = result
        // 1.去vuex中更新用户信息
        store.commit('user/setUser', { id, account, mobile, avatar, token, nickname })
        // 2.提示信息
        app.$message({ type: 'success', text: '登录成功' })
        // 3.跳转
        router.push(route.query.redirectUrl || store.state.user.currentPath)
      } catch (err) {
        // console.log(err)
        app.$message({ type: 'error', text: err.response.data.message || '登录失败', time: 3000 })
      }
    } else {
      // 手机登录
    }
  } else {
    // Message({ type: 'error', text: '校验失败', time: 5000 })
    app.$message({ type: 'error', text: '校验失败', time: 5000 })
  }
}
</script>
<style lang="less" scoped>
// 账号容器
.account-box {
  .toggle {
    padding: 15px 40px;
    text-align: right;

    a {
      color: @xtxColor;

      i {
        font-size: 14px;
      }
    }
  }

  .form {
    padding: 0 40px;

    &-item {
      margin-bottom: 28px;

      .input {
        position: relative;
        height: 36px;

        >i {
          width: 34px;
          height: 34px;
          background: #cfcdcd;
          color: #fff;
          position: absolute;
          left: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 18px;
        }

        input {
          padding-left: 44px;
          border: 1px solid #cfcdcd;
          height: 36px;
          line-height: 36px;
          width: 100%;

          &.error {
            border-color: @priceColor;
          }

          &.active,
          &:focus {
            border-color: @xtxColor;
          }
        }

        .code {
          position: absolute;
          right: 1px;
          top: 1px;
          text-align: center;
          line-height: 35px;
          font-size: 14px;
          //background: #f5f5f5;
          // color: #666;
          width: 90px;
          height: 35px;
          cursor: pointer;
        }
      }

      >.error {
        position: absolute;
        font-size: 12px;
        line-height: 28px;
        color: @priceColor;

        i {
          font-size: 14px;
          margin-right: 2px;
        }
      }
    }

    .agree {
      a {
        color: #069;
      }
    }

    .btn {
      display: block;
      width: 100%;
      height: 40px;
      color: #fff;
      text-align: center;
      line-height: 40px;
      background: @xtxColor;

      &.disabled {
        background: #cfcdcd;
      }
    }
  }

  .action {
    padding: 20px 40px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .url {
      a {
        color: #999;
        margin-left: 10px;
      }
    }
  }
}
</style>